import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/pages/test_questions/test_questions_logic.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

// 7-百分比分配题(QuestionTypePercentageAllocation)
class PercentageAllocationWidget extends StatelessWidget {
  final TestQuestionsLogic logic;

  // 总分数
  final int totalScore = 100;

  const PercentageAllocationWidget({
    super.key,
    required this.logic,
  });

  @override
  Widget build(BuildContext context) {
    final options = logic.currentQuestion?.options ?? [];
    return ListView.separated(
      physics: const BouncingScrollPhysics(),
      padding: EdgeInsets.zero,
      itemCount: options.length,
      separatorBuilder: (context, index) => SizedBox(height: 24.w),
      itemBuilder: (context, index) {
        final option = options[index];
        if (option.id == null) return const SizedBox();

        return _buildScoreItem(context, option, index);
      },
    );
  }

  Widget _buildScoreItem(
      BuildContext context, ModelTestDetailQuestionsOptions option, int index) {
    // final optionId = option.id!;
    final score =
        logic.userAnswers[logic.currentQuestion?.id ?? 0]?[index] ?? 0;
// clog('sc   $score');
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20.w),
        boxShadow: [
          BoxShadow(
            color: AppColor.primary.withOpacity(0.12),
            blurRadius: 11.w,
            offset: Offset(0, 4.w),
          ),
        ],
      ),
      padding: EdgeInsets.fromLTRB(14.w, 14.w, 14.w, 18.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题和分数
          Row(
            children: [
              Expanded(
                child: Text(
                  option.content ?? '',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    color: AppColor.color0C0A09,
                    height: 1.4,
                  ),
                ),
              ),
              SizedBox(width: 12.w),
              Text(
                '$score%',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  color: const Color(0xFF686B76),
                ),
              ),
            ],
          ),
          SizedBox(height: 12.w),

          // 使用Slider组件
          SliderTheme(
            data: SliderTheme.of(context).copyWith(
              activeTrackColor: AppColor.primary,
              inactiveTrackColor: Colors.white,
              trackHeight: 12.w,
              thumbColor: Colors.white,
              thumbShape: RoundSliderThumbShape(
                enabledThumbRadius: 11.w,
                elevation: 4.0,
              ),
              overlayShape: const RoundSliderOverlayShape(overlayRadius: 0),
              tickMarkShape: RoundSliderTickMarkShape(
                tickMarkRadius: 1.w,
              ),
              activeTickMarkColor: Colors.white.withOpacity(0.8),
              inactiveTickMarkColor: Colors.white.withOpacity(0.8),
            ),
            child: Slider(
              value: min(score.toDouble(), 100.0),
              min: 0,
              max: totalScore.toDouble(),
              divisions: totalScore,
              onChanged: (value) {
                // clog('dalksdjlaskd   $value');
                _updateScore(index, value.toInt());
              },
            ),
          ),
        ],
      ),
    );
  }

  // 更新分数
  void _updateScore(int index, int newScore) {
    final questionId = logic.currentQuestion!.id!;
    List<int> points = logic.userAnswers[questionId] ?? [];
    // 计算当前总分数（不包括正在更新的选项）
    int currentTotal = 0;
    for (int i = 0; i < points.length ; i ++) {
      if (i != index) {
        currentTotal += points[i];
      }
    }
    if (currentTotal + newScore > totalScore) {
      newScore = totalScore - currentTotal;
    }

    (logic.userAnswers[questionId] ?? [])[index] = newScore;
    logic.update();
  }
}
